import type { FieldBaseType, FormViewValidate } from "./type";

const InnerFieldValidators: Record<string, FormViewValidate<any>> = {};

export { extendValidator };
export default validator;

function extendValidator(type: string, validate: FormViewValidate<any>) {
  InnerFieldValidators[type] = validate;
}

function validator<T extends FieldBaseType>(
  field: T,
  v: any
): [boolean, string] {
  const { required } = field;

  const isEmpty =
    v === "" ||
    v === null ||
    v === undefined ||
    (Array.isArray(v) && v.length == 0) ||
    Number.isNaN(v);

  /**
   * 空值需要单独校验，看 field 是否要求必填
   * 如果非必填，并且值是空，那么直接返回，这是一个合法的“空值”
   */
  if (isEmpty) return required ? [false, "该字段必填"] : [true, ""];

  const innerValidate = InnerFieldValidators[field.type];
  if (innerValidate) {
    const r = innerValidate?.(v, field);
    if (r) return [r.isValid, r.errmsg || ""];
  }

  if (field.validate) {
    const r = field.validate(v, field);
    if (r && !r.isValid) return [false, r.errmsg || "数据错误"];
  }

  return [true, ""];
}
